package org.example.ims.Controller.Base;

import org.example.ims.DTO.Response;
import org.example.ims.Entity.Base.Salesman;
import org.example.ims.Service.Base.SalesmanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/salesman")
public class SalesmanController {

    @Autowired
    private SalesmanService salesmanService;

    // 根据ID查询销售员
    @GetMapping("/{id}")
    public ResponseEntity<Response<Salesman>> getSalesmanById(@PathVariable Integer id) {
        Optional<Salesman> salesman = salesmanService.getSalesmanById(id);
        if (salesman.isPresent()) {
            return ResponseEntity.ok(Response.success(salesman.get()));
        }
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
                .body(Response.error("NOT_FOUND", "销售员（ID：" + id + "）未找到"));
    }

    // 查询所有销售员（带分页）
    @GetMapping("/search")
    public Response<Page<Salesman>> getAllSalesmen(
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        return Response.success(salesmanService.getAllSalesmen(page, size));
    }

    @GetMapping
    public Response<Page<Salesman>> searchSalesmen(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String department,
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        return Response.success(salesmanService.searchSalesmen(name, department, page, size));
    }

    // 创建销售员
    @PostMapping
    public ResponseEntity<Salesman> createSalesman(@RequestBody Salesman salesman) {
        Salesman savedSalesman = salesmanService.createSalesman(salesman);
        return ResponseEntity.ok(savedSalesman);
    }

    // 更新销售员信息
    @PutMapping("/{id}")
    public ResponseEntity<Salesman> updateSalesman(@PathVariable Integer id, @RequestBody Salesman salesmanDetails) {
        Salesman updatedSalesman = salesmanService.updateSalesman(id, salesmanDetails);
        if (updatedSalesman != null) {
            return ResponseEntity.ok(updatedSalesman);
        }
        return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
    }

    // 删除销售员
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteSalesman(@PathVariable Integer id) {
        salesmanService.deleteSalesman(id);
        return ResponseEntity.ok().build();
    }
}